package com.dgj.mongo.utils;

import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.List;

import org.nutz.lang.Lang;

import com.dgj.mongo.annotation.Collection;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.MongoClient;
import com.mongodb.ServerAddress;

/**
 * Mongo连接池
 * 
 * @author 贵源<br>
 *         Create at 2014年2月23日
 */
public class MongoClientPool extends Mongos {
	/**
	 * 客户端连接
	 */
	private static Connector connector;

	static {
		List<String> servers = Lang.array2list(prop.getProperty("servers").split(","));
		List<ServerAddress> seeds = new ArrayList<ServerAddress>();
		for (String info : servers) {
			try {
				seeds.add(new ServerAddress(prop.getProperty("server-" + info), Integer.parseInt(prop.getProperty("port-" + info))));
			} catch (NumberFormatException e) {
				e.printStackTrace();
			} catch (UnknownHostException e) {
				e.printStackTrace();
			}
		}
		connector = Connector.instants(seeds);
	}

	public static MongoClient getClient() {
		return connector;
	}

	public static DB getDb() {
		return DBConnection.me().getDbConnection(connector, prop.getProperty("dbName"), prop.getProperty("user"), prop.getProperty("pwd"));
	}

	public static DBCollection getCollection(Object object) {
		String name = "";
		Collection collection = null;
		Class<?> clazz = null;
		if (object instanceof Class<?>) {
			collection = ((Class<?>) object).getAnnotation(Collection.class);
			clazz = (Class<?>) object;
		} else {
			collection = object.getClass().getAnnotation(Collection.class);
			clazz = object.getClass();
		}
		if (collection == null) {
			name = clazz.getSimpleName().toLowerCase();
		} else {
			name = collection.value();
		}
		return getDb().getCollection(name);
	}
}
